layui.use(['laytpl', 'table', 'element', 'upload', 'jquery', 'layer', 'laydate'], function() {
    /*解决页面前进返回左侧目录不变化*/
    javascript: parent.moveMenu('pages/fixedUser.html');

    var table = layui.table;
    var element = layui.element;
    var upload = layui.upload;
    var laydate = layui.laydate;
    var laytpl = layui.laytpl;
    var $ = layui.jquery;
    var layer = layui.layer;
    localStorage.removeItem('fixedUser')
    var form = layui.form;
    var loaderIndex = layer.load(1, {
        shade: [0.1, '#fff']
    });


    var exportparams = {}; //导出传参
    var loadeNum = 0; //已请求接口数量
    function closeLoad() { //关闭加载
        loadeNum++;
        if (loadeNum >= 1) {
            layer.close(loaderIndex);
        }
    }

    $('body').off('click').on('click', 'button', function() {
        $(this).blur();
    })
    var nowData = Storage.get('nowData');
    // console.log(nowData)
    var btnData = nowData.children;

    var toolBar = '<div><button class="layui-btn resetBtn" lay-event="edit"><i class="iconfont">&#xe629;</i>编辑</button></div>';
    if (findIndex(btnData, '/addOrUpdate') == -1) { //无修改权限
        toolBar = '<div><button class="layui-btn updateBtn2 resetBtn" style="color: #000;cursor:auto;" >-</button></div>';
    }
    if (findIndex(btnData, '/query') == -1) { //无查询权限
        $('.query').addClass('layui-hide');
    }
    if (findIndex(btnData, 'addOrUpdateVehicle') == -1) { //无添加权限
        // $('.add').addClass('layui-hide');
    }
    if (findIndex(btnData, '/delVehicleBatch') == -1) { //无删除权限
        $('.delete').addClass('layui-hide');
    }
    if (findIndex(btnData, 'xcelTemplateDownload') == -1) { //无下载导入模板权限
        $('.download').addClass('layui-hide');
    }
    if (findIndex(btnData, '/addExcelTemplateData') == -1) { //无导入权限
        $('.import').addClass('layui-hide');
    }
    if (findIndex(btnData, 'vehicleExcelExport') == -1) { //无导出权限
        $('.export').addClass('layui-hide');
    }
    if (findIndex(btnData, 'updateVehicleBatch') == -1) { //无批量设置权限
        $('.batchUpdate').addClass('layui-hide');
    }
    // if (findIndex(btnData, 'updateCarPositionsBatch') == -1) { //无批量权限
    //     $('.update').addClass('layui-hide');
    // }

    //"empType": 人员类型0平台管理员1运营商管理员2加油站员工
    var empInfo = Storage.get('empInfo');
    var empType = empInfo.empType;
    var mergeData = [];
    var parkId = ''
    var optGroupId = ""
        //查询数据

    var queryVehicleByPageSelect = JSON.parse(sessionStorage.getItem("queryVehicleByPageSelect"));
    
    if (JSON.stringify(queryVehicleByPageSelect) == "null") {

        // 停车场查询
        var parks = ''
        var params9 = $.extend({}, publicData);
        $.ajax({
            url: httpUrl + 'userPark/getUserPark',
            type: "POST",
            headers: headData,
            data: JSON.stringify(params9),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                // console.log(res)  
                if (res.returnCode == 'SUCCESS') {
                    parks = res.data;
                    var data = {
                        list: parks
                    }

                    var getTpl = parkList2.innerHTML,
                        view = document.getElementById('parkName2');

                    laytpl(getTpl).render(data, function(html) {
                        view.innerHTML = html;

                    })
                    if (parks != null && parks.length > 0) {
                        parkId = parks[0].id
                        $("#parkName2").val(parks[0].id)

                        var queryVehicleGroup = $.extend({}, publicData);
                        queryVehicleGroup.parkId = parks[0].id

                        queryVehicleGroups(queryVehicleGroup)
                    }
                    form.render();
                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                    }
                }
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
                //console.log(xhr); 
            }

        })

    } else {
        var queryVehicleByPage = $.extend({}, publicData);
        var queryVehicleGroup = $.extend({}, publicData);
        var parks = ''
        var params9 = $.extend({}, publicData);
        $.ajax({
            url: httpUrl + 'userPark/getUserPark',
            type: "POST",
            headers: headData,
            data: JSON.stringify(params9),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                // console.log(res)  
                if (res.returnCode == 'SUCCESS') {
                    parks = res.data;
                    var data = {
                        list: parks
                    }

                    var getTpl = parkList2.innerHTML,
                        view = document.getElementById('parkName2');

                    laytpl(getTpl).render(data, function(html) {
                        view.innerHTML = html;

                    })

                    $("#parkName2").val(queryVehicleByPageSelect.parkId)
                    form.render();
                    parkId = queryVehicleByPageSelect.parkId
                    queryVehicleGroup.parkId = queryVehicleByPageSelect.parkId
                    queryVehicleByPage.parkId = queryVehicleByPageSelect.parkId
                    queryVehicleGroups(queryVehicleGroup)


                    form.render();
                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                    }
                }
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
                //console.log(xhr); 
            }
        })
    }
    var queryVehicleByPage = JSON.parse(sessionStorage.getItem("queryVehicleByPage"));
    if (JSON.stringify(queryVehicleByPage) != "null") {
        $("#test1").val(queryVehicleByPage.beginTimeStr)
        $("#test2").val(queryVehicleByPage.endTimeStr)
        var params10 = $.extend({}, publicData);
        params10.parkId = queryVehicleByPage.parkId;
        // getSections(params10, 1)
        setTimeout(function() {
            form.val("example", {
                "beginTimeStr": queryVehicleByPage.beginTimeStr,
                "endTimeStr": queryVehicleByPage.endTimeStr,
                "ownerName": queryVehicleByPage.ownerName,
                "carNum": queryVehicleByPage.carNum,
                "ownerPhone": queryVehicleByPage.ownerPhone,
                "ownerCompany": queryVehicleByPage.ownerCompany,
                "ownerAddress": queryVehicleByPage.ownerAddress,

            });
            $("#parkName2").val(queryVehicleByPage.parkId)

        }, 1000)

        allData(queryVehicleByPage);

    } else {
        queryVehicleByPage = $.extend({}, publicData);
        allData(queryVehicleByPage);
    }

    var time1 = '',
        time2 = '';
    laydate.render({
        elem: '#test1',
        trigger: 'click',
        done: function(value, date, endDate) {
            time1 = value;
            jude();
        }
    });
    laydate.render({
        elem: '#test2',
        trigger: 'click',
        done: function(value, date, endDate) {
            time2 = value;
            jude();
        }
    });

    // 检测开始时间不能大于结束时间
    function jude() {
        if (time1 && time2) {
            if (!judgeTime(time1, time2)) {
                layer.msg('开始时间不能大于结束时间', {
                    icon: 2
                });
                setTimeout(function() {
                    form.val('example', {
                        failureBeginTimeStr: '',
                        failureEndTimeStr: ''
                    })
                    time1 = '';
                    time2 = '';
                }, 1000)

            }
        }
    }






    function allData(queryVehicleByPage) {

        queryVehicleByPage.isOpenPage = true;
        exportparams = $.extend({}, queryVehicleByPage);
        table.render({
            elem: '#freeTable',
            url: httpUrl + 'vehicle/queryVehicleByPage',
            request: {
                pageName: 'start' //页码的参数名称,默认：page
            },
            method: 'POST',
            contentType: "application/json",
            where: queryVehicleByPage,
            id: 'freeTable',
            headers: headData,
            response: {
                statusCode: 'SUCCESS'
            },

            height: height,
            parseData: function(res) { //res 即为原始返回的数据

                return {
                    "code": res.returnCode, //解析接口状态
                    "msg": res.returnMsg, //解析提示文本
                    "count": res.data ? res.data.total : 0, //解析数据长度
                    "data": res.data ? res.data.list : []

                };
            },

            done: function(res) {
                //console.log(res)
                mergeData = [];
                control1 = true;
                closeLoad();

                //token 失效
                if (res.code == 'UNAUTHORIZED') {
                    checkToken();
                }


            },
            fail: function(e, t) {
                control1 = true;
                closeLoad();
            },
            page: true,
            limit: 11,
            limits: [11, 20, 40, 60, 80, 100],
            height: height,
            cols: [
                [{
                        field: 'checkbox',
                        title: '选择',
                        align: 'center',
                        type: 'checkbox',
                        width: 50,

                    }, {
                        title: '序号',
                        align: 'center',
                        // field: 'serialNumber',
                        type: "numbers",
                        width: 50,

                    }, {
                        field: 'parkName',
                        title: '所属停车场',
                        align: 'center',
                        width: 150

                    }, {
                        field: 'ownerName',
                        title: '用户名称',
                        align: 'center',
                        width: 200
                    }, {
                        field: 'ownerPhone',
                        title: '手机号码',
                        align: 'center',
                        width: 90
                    }, {
                        templet: function(d) {
                            if (d.tbVehicleListDtos.length > 1) {
                                var div1 = document.createElement("div");
                                div1.id = "divBox";
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {
                                    var carNum = document.createElement("div")
                                    carNum.classList.add("sectionName")
                                    carNum.innerText = d.tbVehicleListDtos[j].carNum
                                    div1.append(carNum)
                                }
                                return div1.innerHTML;
                            } else {
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {
                                    var carNum = d.tbVehicleListDtos[j].carNum
                                }
                                return '<div>' + carNum + '</div>'
                            }
                        },
                        field: 'carNum',
                        title: '车牌号码',
                        align: 'center',
                        // width: 100
                    }, {
                        templet: function(d) {
                            if (d.tbVehicleListDtos.length > 1) {
                                var div1 = document.createElement("div");
                                div1.id = "divBox";
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {

                                    var beginTimeStr = document.createElement("div")
                                    beginTimeStr.classList.add("beginDateStr")
                                    beginTimeStr.innerText = d.tbVehicleListDtos[j].beginTimeStr
                                    div1.append(beginTimeStr)
                                }
                                return div1.innerHTML;
                            } else {
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {
                                    beginTimeStr = getTime(d.tbVehicleListDtos[j].beginTimeStr, 3, '-')
                                }
                                return '<div>' + beginTimeStr + '</div>'
                            }
                        },
                        field: 'beginTimeStr',
                        title: '生效时间',
                        align: 'center',
                        width: 150
                    }, {
                        templet: function(d) {
                            if (d.tbVehicleListDtos.length > 1) {
                                var div1 = document.createElement("div");
                                div1.id = "divBox";
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {
                                    var endTimeStr = document.createElement("div")
                                    endTimeStr.classList.add("beginDateStr")
                                    endTimeStr.innerText = d.tbVehicleListDtos[j].endTimeStr
                                    div1.append(endTimeStr)
                                }
                                return div1.innerHTML;
                            } else {
                                for (var j = 0; j < d.tbVehicleListDtos.length; j++) {
                                    var endTimeStr = d.tbVehicleListDtos[j].endTimeStr
                                }
                                return '<div>' + endTimeStr + '</div>'
                            }
                        },
                        field: 'endTimeStr',
                        title: '失效时间',
                        align: 'center',
                        width: 150

                    }, {
                        field: 'ownerCompany',
                        title: '单位名称',
                        align: 'center',
                        width: 200
                    }, {

                        field: 'ownerAddress',
                        title: '地址',
                        align: 'center',
                        width: 200
                    },
                    {
                        field: 'operating',
                        title: '操作',
                        align: 'center',
                        toolbar: '',
                        templet: toolBar,
                        width: 100
                    }
                ]
            ]
        });
    }
    // 表格操作
    table.on('tool(freeTable)', function(obj) {
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if (layEvent == "edit") { //编辑
            obj.data.groupId = optGroupId;
            Storage.set('fixedUser', obj.data);
            parent.document.getElementsByClassName("layui-show")[0].children[0].src = "pages/addFixedUser.html";
        }
    })
    var setData = [];
    var delDatas = [];
    table.on('checkbox(freeTable)', function(obj) {
        var checkData = table.checkStatus('freeTable').data;

        if (checkData.length > 0) {
            parkId = checkData[0].parkId
            if (obj.type == "one") {
                delDatas = checkData.map(function(item, index) {

                    if (checkData[index].parkId != parkId) {
                        checkData.splice(index, 1)
                        $('.layui-table-box ' + obj.tr.selector + '').find('div.layui-form-checked').click();
                        layer.msg('所选数据不是同一个停车场，无法批量操作', {
                            icon: 5
                        });
                        return
                    } else {
                        return item.id = item.id
                    }
                });
                setData = checkData.map(function(item) {
                    return item = item
                });
            } else {
                delDatas = checkData.map(function(item, index) {

                    if (checkData[index].parkId != parkId) {
                        checkData.splice(index, 1)
                            // $('.layui-table-box ' + obj.tr.selector + '').find('div.layui-form-checked').click();
                        $('.layui-table-box .layui-table tr:first-child').find('div.layui-form-checked').click();
                        layer.msg('所选数据不是同一个停车场，无法批量操作', {
                            icon: 5
                        });
                    } else {
                        return item.id = item.id
                    }
                });
                setData = checkData.map(function(item) {
                    return item = item
                });
            }


        } else {
            delDatas = [];
            setData = [];
        }
    });

    //查询 
    var control1 = true;
    form.on('submit(formDemo)', function(data) {
        if (control1) {
            control1 = false;
            loaderIndex = layer.load(1, {
                shade: [0.1, '#fff']
            });
            var val = data.field;
            var queryVehicleByPage = $.extend({}, publicData);
            queryVehicleByPage = $.extend(queryVehicleByPage, val);
            queryVehicleByPage.groupId = optGroupId;
            queryVehicleByPage.parkId = parkId;
            sessionStorage.setItem("queryVehicleByPage", JSON.stringify(queryVehicleByPage));
            allData(queryVehicleByPage);
        }
    });
    // 添加固定用户
    add = function() {
        if (parkId == '' || optGroupId == '') {
            layer.msg("请先选择所属停车场及用户组", {
                icon: 2
            });
        } else {
            var fixedUserInfo = {}
            fixedUserInfo.parkId = parkId;
            fixedUserInfo.groupId = optGroupId
            Storage.set('fixedUserInfo', fixedUserInfo);
            parent.document.getElementsByClassName("layui-show")[0].children[0].src = "pages/addFixedUser.html";
        }
    }
    var params6 = $.extend({}, publicData);
    params6.token = headData.token;
    // 导入数据入口
    importWrap = function() {
        $('.restBtn2').click();
        if (parkId != '' || optGroupId == '') {
            params6.parkId = parkId;
            params6.file = "xls";
            params6.groupId = optGroupId;
            $('#importBtn').click();
        } else {
            layer.msg("请先选择所属停车场及用户组", {
                icon: 2
            });
        }
    }

    //导入数据
    var uploadMsg;
    var uploadInst = upload.render({
        elem: '#importBtn', //绑定元素
        url: httpUrl + 'vehicle/addExcelTemplateData', //上传接口
        data: params6,
        accept: 'file',
        size: 1024,
        before: function(o) {
            uploadMsg = layer.msg('上传中', {
                icon:16,shade: [0.1, '#fff'],time:false
            });
        },
        done: function(res) {
            if (res.returnCode == 'SUCCESS') {
                layer.msg(res.returnMsg, {
                    icon: 1
                });
                allData(queryVehicleByPage)
            } else {
                if (res.returnCode == 'UNAUTHORIZED') {
                    checkToken();
                } else {
                    layer.msg(res.returnMsg, {
                        icon: 2
                    });
                    layer.alert(res.returnMsg)
                }
            }
            layer.close(uploadMsg);
        },
        error: function(res) {
            layer.msg('网络异常', {
                icon: 2
            });
            layer.close(uploadMsg);
        }
    });
    //下载模板
    exportData = function(item) {
        var userAgent = window.navigator.userAgent;
        var exporData = {};
        if (userAgent.indexOf('Firefox') != -1) {
            exporData.isIE = 0;
        } else {
            exporData.isIE = 1;
        }
        var URL = httpUrl + 'vehicle/excelTemplateDownload';
        download(exporData, URL, '固定用户导入模板');
    }
    //导出
    exportDatas = function() {
        var userAgent = window.navigator.userAgent;
        if (userAgent.indexOf('Firefox') != -1) {
            exportparams.isIE = 0;
        } else {
            exportparams.isIE = 1;
        }
        exportparams.isOpenPage = false;
        var URL = httpUrl + 'vehicle/vehicleExcelExport';
        download(exportparams, URL, '固定用户组信息');
    }
    //删除
    var control3 = true;
    del = function() {
        if (delDatas.length > 0) {

            layer.confirm('确认删除?', { icon: 7, title: '提示' }, function(index) {
                layer.close(index);
                if (control3) {
                    control3 = false;
                    var load0 = layer.load(2);
                    var delVehicleBatch = $.extend({}, publicData);
                    delVehicleBatch.parkId = parkId;
                    let deletedTbVehicleOwnerIds = [];
                    delDatas.forEach(element => {
                        deletedTbVehicleOwnerIds.push(element)
                    });
                    delVehicleBatch.deletedTbVehicleOwnerIds = deletedTbVehicleOwnerIds;
                    $.ajax({
                        url: httpUrl + 'vehicle/delVehicleBatch',
                        type: "POST",
                        headers: headData,
                        data: JSON.stringify(delVehicleBatch),
                        contentType: "application/json",
                        dataType: "json",
                        success: function(res) {
                            //console.log(res);
                            if (res.returnCode == 'SUCCESS') {
                                layer.msg(res.returnMsg, {
                                    icon: 1
                                });
                                setTimeout(function() {
                                    refresh();
                                }, 1500)
                            } else {
                                if (res.returnCode == 'UNAUTHORIZED') {
                                    checkToken();
                                } else {
                                    layer.msg(res.returnMsg, {
                                        icon: 2
                                    });
                                }
                            }
                            control3 = true;
                            layer.close(load0);
                        },
                        error: function(xhr) {
                            layer.msg('网络异常', {
                                icon: 2
                            });
                            control3 = true;
                            layer.close(load0);
                            //console.log(xhr); 
                        }
                    })
                }
            });

        } else {
            layer.msg('您还没有选择任何数据', {
                icon: 2
            });
        }
    }
    // 单选
    form.on('radio(typeTime)', function(data) {
        if (data.value == 0) {
            $('.modify2').addClass('layui-hide');
            $('.modify1').removeClass('layui-hide');
            $("#times3").val('')
        } else {
            $('.modify1').addClass('layui-hide');
            $('.modify2').removeClass('layui-hide');
            $("#times").val('')
        }
    });

    // 用户车辆组查询及其操作
    var filenum = 0

    var queryVehicleGroup = $.extend({}, publicData);
    var addOrUpdateVehicleGroup = $.extend({}, publicData);
    var queryVehicleByPage = $.extend({}, publicData);
    var delData = ''
    form.on('select(userParkId)', function(data) {
        filenum = 0
        parkId = data.value;
        addOrUpdateVehicleGroup.parkId = parkId;
        queryVehicleGroup.parkId = parkId;
        queryVehicleByPage.parkId = parkId
        queryVehicleGroups(queryVehicleGroup);
        allData(queryVehicleByPage)
        queryVehicleByPage.parkId = parkId;
        sessionStorage.setItem("queryVehicleByPageSelect", JSON.stringify(queryVehicleByPage));
    });




    function queryVehicleGroups(queryVehicleGroup) {
        optGroupId = null;
        var load0 = layer.load(2);
        form.render('select')
        $.ajax({
            url: httpUrl + 'vehicleGroup/queryVehicleGroup',
            type: "POST",
            headers: headData,
            data: JSON.stringify(queryVehicleGroup),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                //console.log(res);
                if (res.returnCode == 'SUCCESS') {
                    delData = res.data
                    $(".leftBox .userBox").empty()
                    var ul = "<ul class='userList'></ul>"
                    $(".leftBox .userBox").append(ul)
                    if (delData.length != 0) {


                        for (let index in res.data) {
                            res.data[index].i = index
                            var li = "<li>" +
                                "<span>" + res.data[index].groupName + "</span>" +
                                "<p class='setting'id='set" + res.data[index].i + "' onclick='setUser(id)'>设置</p>" +
                                "<p id=" + res.data[index].i + " onclick='delLi(id)'>删除</p></li>"
                            $(".userList").append(li)
                        }
                        $(".leftBox .userBox .userList li:first").addClass("opt")
                        var queryVehicleByPage = $.extend({}, publicData);
                        queryVehicleByPage.parkId = parkId
                        optGroupId = delData[0].id
                        queryVehicleByPage.groupId = delData[0].id;
                        var fixedUserInfo = {}
                        fixedUserInfo.parkId = parkId;
                        fixedUserInfo.groupId = optGroupId
                        Storage.set('fixedUserInfo', fixedUserInfo);
                        allData(queryVehicleByPage);

                    } else {
                        var queryVehicleByPage = $.extend({}, publicData);
                        if (JSON.stringify(queryVehicleByPageSelect) == "null") {

                            queryVehicleByPage.parkId = queryVehicleGroup.parkId
                            allData(queryVehicleByPage);
                        } else {
                            queryVehicleByPage.parkId = queryVehicleGroup.parkId
                            allData(queryVehicleByPage);
                        }

                    }
                    var addLi = "<p class='addLi' onclick='addLi()'>新增</p>"
                    $(".userBox").append(addLi)
                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                    }
                }
                control5 = true;
                layer.close(load0);
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
                control1 = true;
                layer.close(load0);
                //console.log(xhr); 
            }

        })
    }
    // 选择用户组

    var oldIndex = ''
    $(".leftBox .userBox ").on('click', '.userList li', function() {
        $(this).siblings('li').removeClass('opt');
        $(this).addClass("opt")
        oldIndex = $(this).index()
        optGroupId = delData[$(this).index()].id
        var fixedUserInfo = {}
        fixedUserInfo.parkId = parkId;
        fixedUserInfo.groupId = optGroupId
        Storage.set('fixedUserInfo', fixedUserInfo);
        queryVehicleByPage.groupId = optGroupId
        queryVehicleByPage.parkId = delData[$(this).index()].parkId
        allData(queryVehicleByPage)
    })


    // 新增用户组
    addLi = function() {

        setUser()
    }
    // $(".leftBox .userBox ").on('blur', '.userList #new input', function() {
    //     var load0 = layer.load(2);
    //     addOrUpdateVehicleGroup.groupName = $(".leftBox .userBox .userList #new input").val()
    //     addOrUpdateVehicleGroup.parkId = parkId
    //     addOrUpdateVehicleGroups(addOrUpdateVehicleGroup)
    //     setTimeout(function() {
    //         // console.log($(".leftBox .userBox .userList li:last").html())
    //         $(".leftBox .userBox .userList li:last p:first").click()
    //     }, 500);
    // })
    addOrUpdateVehicleGroups = function(addOrUpdateVehicleGroup) {
        $.ajax({
            url: httpUrl + 'vehicleGroup/addOrUpdateVehicleGroup',
            type: "POST",
            headers: headData,
            data: JSON.stringify(addOrUpdateVehicleGroup),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                // console.log(res)  
                if (res.returnCode == 'SUCCESS') {

                    var queryVehicleGroup = $.extend({}, publicData);
                    queryVehicleGroup.parkId = parkId
                    queryVehicleGroups(queryVehicleGroup)
                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                    }
                }
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
            }

        })
    }
    // 删除用户组
    delLi = function(index) {
		layer.confirm('确认删除?', { icon: 7, title: '提示' }, function(index1) {
			layer.load(2, {
			  shade: [0.3,'#fff'] //0.1透明度的白色背景
			});
			var delVehicleGroup = $.extend({}, publicData);
			delVehicleGroup.parkId = delData[index].parkId
			delVehicleGroup.id = delData[index].id
			$.ajax({
			    url: httpUrl + 'vehicleGroup/delVehicleGroup',
			    type: "POST",
			    headers: headData,
			    data: JSON.stringify(delVehicleGroup),
			    contentType: "application/json",
			    dataType: "json",
			    success: function(res) {
			        // console.log(res)  
			        if (res.returnCode == 'SUCCESS') {
			            layer.msg(res.returnMsg, {
			                icon: 1
			            });
			            setTimeout(function() {
			
			                refresh();
			            }, 1500)
			        } else {
			            //token 失效
			            if (res.returnCode == 'UNAUTHORIZED') {
			                checkToken();
			            } else {
			                layer.msg(res.returnMsg, {
			                    icon: 2
			                });
			            }
			        }
			    },
			    error: function(xhr) {
			        layer.msg('网络异常', {
			            icon: 2
			        });
			    }
			})
		})
        
    }
    // 设置用户组
    var userTime1 = '',
        userTime12 = '';
    laydate.render({
        elem: '#beginTimeStr',
        trigger: 'click',
        type: 'time',
        done: function(value, date, endDate) {
            userTime1 = value;
            // jude();
        }
    });
    laydate.render({
        elem: '#endTimeStr',
        trigger: 'click',
        type: 'time',
        done: function(value, date, endDate) {
            userTime12 = value;
            // jude();
        }
    });

    $('.modify2').addClass('layui-hide');
    $('.modify1').removeClass('layui-hide');
    // 单选
    form.on('radio(type)', function(data) {
        if (data.value == 0) {
            $("#perFreeTime").val('')
            $("#discount").val('')
            $("#beginTimeStr").removeAttr('disabled')
            $("#endTimeStr").removeAttr('disabled')
            $("#perFreeTime").attr('disabled', 'disabled')
            $("#discount").attr('disabled', 'disabled')
        } else if (data.value == 1) {
            $("#beginTimeStr").val('')
            $("#endTimeStr").val('')
            $("#discount").val('')
            $("#beginTimeStr").attr('disabled', 'disabled')
            $("#endTimeStr").attr('disabled', 'disabled')
            $("#perFreeTime").removeAttr('disabled')
            $("#discount").attr('disabled', 'disabled')
        } else {
            $("#beginTimeStr").val('')
            $("#endTimeStr").val('')
            $("#perFreeTime").val('')
            $("#beginTimeStr").attr('disabled', 'disabled')
            $("#endTimeStr").attr('disabled', 'disabled')
            $("#perFreeTime").attr('disabled', 'disabled')
            $("#discount").removeAttr('disabled')
        }
    });
    setUser = function(indexs) {



        // 恢复默认值
        $("input[name=type][value=0]").prop("checked", false)
        $("input[name=type][value=1]").prop("checked", false)
        $("input[name=type][value=2]").prop("checked", false)
        $("#beginTimeStr").attr('disabled', 'disabled')
        $("#endTimeStr").attr('disabled', 'disabled')
        $("#perFreeTime").attr('disabled', 'disabled')
        $("#discount").attr('disabled', 'disabled')
        form.val('userChangeBox', {
            beginTimeStr: '',
            endTimeStr: '',
            groupName: '',
            perFreeTimeStr: '',
            discount: ''
        })
        form.render();
        if (indexs) {
            indexs = indexs.substring(3)
            $("#groupName").val(delData[indexs].groupName)
            var queryVehicleGroupRule = $.extend({}, publicData);
            queryVehicleGroupRule.parkId = delData[indexs].parkId
            queryVehicleGroupRule.groupId = delData[indexs].id
            queryVehicleGroupRules(queryVehicleGroupRule)
        } else {
            addOrUpdateVehicleGroupRuleDatas = []
        }
        if (window.screen.width > 1024) {
            screenWidth = "50%"
            screenHeight = "75%"
        } else {
            screenWidth = "80%"
            screenHeight = "80%"
        }
        layer.open({
            title: '设置用户组',
            type: 1,
            maxmin: true,
            shade: [0.8, '#393D49'],
            shadeClose: false,
            area: [screenWidth, screenHeight],
            content: $('#userWrap'),
            btn: ['确定', '取消'],
            yes: function(index, layero) {
                form.on('submit(userChangeBox)', function(data) {
                    var val = data.field;
                    var addOrUpdateVehicleGroupRule = $.extend({}, publicData);
                    var tbVehicleGroupRuleVo = $.extend({}, publicData);
                    var tbVehicleGroup = $.extend({}, publicData);
                    addOrUpdateVehicleGroupRule.parkId = parkId;
                    if (addOrUpdateVehicleGroupRuleDatas.length != 0) {
                        // 有组名称 有规则
                        tbVehicleGroup.id = delData[indexs].id;
                        tbVehicleGroup.groupName = $("#groupName").val();
                        addOrUpdateVehicleGroupRule.tbVehicleGroup = tbVehicleGroup;
                        tbVehicleGroupRuleVo = $.extend({}, val);
                        tbVehicleGroupRuleVo.groupId = addOrUpdateVehicleGroupRuleDatas[0].groupId;
                        tbVehicleGroupRuleVo.id = addOrUpdateVehicleGroupRuleDatas[0].id;
                        addOrUpdateVehicleGroupRule.tbVehicleGroupRuleVo = tbVehicleGroupRuleVo;
                    } else {
                        // 没名称 没规则
                        tbVehicleGroup.groupName = $("#groupName").val();
                        addOrUpdateVehicleGroupRule.tbVehicleGroup = tbVehicleGroup;
                        tbVehicleGroupRuleVo = $.extend({}, val);
                        addOrUpdateVehicleGroupRule.tbVehicleGroupRuleVo = tbVehicleGroupRuleVo;
                    }
                    if (val.groupName != '') {
                        if (val.beginTimeStr != '' || val.discount != '' || val.perFreeTimeStr != '') {
                            if (val.perFreeTimeStr != '') {
                                if (val.perFreeTimeStr > 9999 || val.perFreeTimeStr < 0.1) {
                                    layer.msg('请输入0-10000之间的数值', {
                                        icon: 2
                                    });
                                    $("#perFreeTime").val('');
                                } else {
                                    setUsers(addOrUpdateVehicleGroupRule, index, indexs);
                                }
                            } else if (val.discount != '') {
                                var discountReg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,1})?$/;
                                if (!discountReg.test(parseFloat(val.discount))) {
                                    layer.msg('小数点后最多输入一位', {
                                        icon: 2
                                    });
                                    $("#discount").val('');
                                } else if (val.discount > 9.9 || val.discount < 0.1) {
                                    layer.msg('请输入0-10之间的数值', {
                                        icon: 2
                                    });
                                    $("#discount").val('');
                                } else {
                                    setUsers(addOrUpdateVehicleGroupRule, index, indexs);
                                };
                            } else {
                                setUsers(addOrUpdateVehicleGroupRule, index, indexs);
                            }
                        } else {
                            layer.msg("请设置组规则", {
                                icon: 2
                            });
                        };
                    } else {
                        layer.msg("请设置组名称", {
                            icon: 2
                        });
                    };
                })
                $('.userbtn').click();
            }
        })
    }
    setUsers = function(addOrUpdateVehicleGroupRule, index, indexs) {
        $.ajax({
            url: httpUrl + 'vehicle/addOrUpdateVehicleGroupAndVehicleGroupRule',
            type: "POST",
            headers: headData,
            data: JSON.stringify(addOrUpdateVehicleGroupRule),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                // console.log(res)  
                if (res.returnCode == 'SUCCESS') {
                    layer.msg(res.returnMsg, {
                        icon: 1
                    });
                    layer.close(index);
                    var queryVehicleGroup = $.extend({}, publicData);
                    if (indexs) {

                        queryVehicleGroup.parkId = delData[indexs].parkId
                        queryVehicleGroups(queryVehicleGroup)
                    } else {

                        queryVehicleGroup.parkId = parkId

                        queryVehicleGroups(queryVehicleGroup)
                    }


                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                        layer.close(index);
                    }
                }
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
                layer.close(index);
            }
        })

    }
    // 查询用户组规则
    var addOrUpdateVehicleGroupRuleDatas = ""
    queryVehicleGroupRules = function(queryVehicleGroupRule) {
        $.ajax({
            url: httpUrl + 'vehicleGroupRule/queryVehicleGroupRule',
            type: "POST",
            headers: headData,
            data: JSON.stringify(queryVehicleGroupRule),
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                if (res.returnCode == 'SUCCESS') {
                    layer.msg(res.returnMsg, {
                        icon: 1
                    });
                    addOrUpdateVehicleGroupRuleDatas = []
                    if (res.data.length != 0) {


                        addOrUpdateVehicleGroupRuleDatas = res.data
                        if (res.data[0].beginTimeStr != null) {
                            $("input[name=type][value=0]").prop("checked", true)
                            $("#beginTimeStr").val(res.data[0].beginTimeStr);
                            $("#endTimeStr").val(res.data[0].endTimeStr);
                            $("#beginTimeStr").removeAttr('disabled')
                            $("#endTimeStr").removeAttr('disabled')
                        } else if (res.data[0].perFreeTime != null) {
                            $("input[name=type][value=1]").prop("checked", true)
                            var perFreeTime = res.data[0].perFreeTime / 3600;
                            $("#perFreeTime").val(perFreeTime);
                            $("#perFreeTime").removeAttr('disabled')
                        } else if (res.data[0].discount != null) {
                            $("input[name=type][value=2]").prop("checked", true)
                            $("#discount").val(res.data[0].discount)
                            $("#discount").removeAttr('disabled')
                        }

                    } else {
                        addOrUpdateVehicleGroupRuleDatas = res.data
                    }

                    form.render("radio");


                } else {
                    //token 失效
                    if (res.returnCode == 'UNAUTHORIZED') {
                        checkToken();
                    } else {
                        layer.msg(res.returnMsg, {
                            icon: 2
                        });
                    }
                }
            },
            error: function(xhr) {
                layer.msg('网络异常', {
                    icon: 2
                });
            }
        })
    }
    // 重置回调
    resetB = function() {
        time1 = '';
        time2 = '';
    }
    // 查询
    refresh = function() {
        history.go(0)

    }
    back = function() {
        history.back(-1)
    }

    //解决火狐刷新搜索条件还在的问题 example
    // $('.resetB').click();
    form.val('example', {
        parkId: ''
    })

    // 批量设置
    setting = function() {
        debugger
        if (!parkId) {
            layer.msg('请选择停车场！', {icon: 0});
            return;
        }
        if (!optGroupId) {
            layer.msg('请选择用户组！', {icon: 0});
            return;
        }
        // 获取数据
        var param = $.extend({}, publicData);
        param.parkId = parkId;
        param.groupId = optGroupId;
        param.ownerName = $("#ownerName").val();
        param.carNum = $("#carNum").val();
        param.ownerPhone = $("#ownerPhone").val();
        param.ownerCompany = $("#ownerCompany").val();
        param.ownerAddress =  $("#ownerAddress").val();
        param.beginTimeStr = $("#test1").val();
        param.endTimeStr = $("#test2").val();
        var screenWidth = '';
        var screenHeight = '';

        if (window.screen.width > 1024) {
            screenWidth = "40%";
            screenHeight = "50%";
        } else {
            screenWidth = "50%";
            screenHeight = "60%";
        }
        $("#timeBox").empty()
        var times = '<input type="text" name="times3" class="layui-input" id="test3" autocomplete="off" placeholder="yyyy-MM-dd" style="background:url(../img/date_20180730.png) no-repeat;background-position:93% 9px;">'
        $("#timeBox").append(times)
        $("#times").val("");
        $("#test3").val("");
        var nowTime = getTime(new Date(), 3, '-');
        laydate.render({
            elem: '#test3',
            trigger: 'click',
            min: nowTime,
            done: function(value, date, endDate) {
                param.invalidTimeStr = value;
            }
        });
        layer.open({
            type: 1,
            anim: 5,
            shade: [0.8, '#393D49'],
            shadeClose: false,
            title: '批量设置失效时间',
            area: [screenWidth, screenHeight],
            closeBtn: false,
            content: $('#wrap1'),
            btn: ['确定', '取消'],
            btn1: function(index, layero) {
                if(!param.invalidTimeStr) {
                    layer.msg('请选择失效时间！', {icon: 0});
                    return;
                } else {
                    layer.confirm('批量设置后不可恢复，确认操作？', {
                        btn: ['确定', '取消']
                    }, function () {
                        $.ajax({
                            url: httpUrl + 'vehicle/updateVehicleBatch',
                            type: "POST",
                            headers: headData,
                            data: JSON.stringify(param),
                            contentType: "application/json",
                            dataType: "json",
                            success: function(res) {
                                if (res.returnCode == 'SUCCESS') {
                                    layer.msg(res.returnMsg, {
                                        icon: 1
                                    });
                                    setTimeout(function() {
                                        layer.close(index);
                                        refresh();
                                    }, 1500)
                                } else {
                                    if (res.returnCode == 'UNAUTHORIZED') {
                                        checkToken();
                                    } else {
                                        layer.msg(res.returnMsg, {
                                            icon: 2
                                        });
                                    }
                                }
                                layer.close(index);
                            },
                            error: function(xhr) {
                                layer.msg('网络异常', {
                                    icon: 2
                                });
                                layer.close(index);
                            }
                        })
                    }, function () {
                        layer.close(index);
                    });
                }
            },
            btn2: function(index, layero) {
                layer.close(index);
            }
        });
    }

});